package com.note.common.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 极光短信服务
 * 封装极光短信API调用
 */
@Slf4j
@Service
public class JiGuangSmsService {

    @Value("${jiguang.sms.app-key}")
    private String appKey;

    @Value("${jiguang.sms.master-secret}")
    private String masterSecret;

    @Value("${jiguang.sms.sign-id:}")
    private String signId;

    @Value("${jiguang.sms.base-url}")
    private String baseUrl;

    @Value("${jiguang.sms.temp-id-login}")
    private String tempIdLogin;

    @Value("${jiguang.sms.temp-id-register}")
    private String tempIdRegister;

    @Value("${jiguang.sms.temp-id-reset-password}")
    private String tempIdResetPassword;

    @Autowired
    @Qualifier("externalRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送验证码短信
     *
     * @param mobile 手机号
     * @param type   验证码类型 LOGIN/REGISTER/PASSWORD_RESET
     * @return 发送结果，包含msgId或错误信息
     */
    public SmsResult sendVerificationCode(String mobile, String type) {

        // 暂时关闭短信发送
        log.info("短信发送功能已关闭");
        if (true) {
            return SmsResult.error("短信发送功能已关闭");
        }

        String tempId = getTemplateIdByType(type);
        if (tempId == null) {
            log.error("无效的验证码类型: {}", type);
            return SmsResult.error("无效的验证码类型");
        }

        try {
            String url = baseUrl + "/codes";
            HttpHeaders headers = createAuthHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("mobile", mobile);
            requestBody.put("temp_id", Integer.parseInt(tempId));

            // 如果签名ID不为空，则添加到请求中
            if (signId != null && !signId.isEmpty()) {
                requestBody.put("sign_id", Integer.parseInt(signId));
            }

            HttpEntity<String> requestEntity = new HttpEntity<>(
                    objectMapper.writeValueAsString(requestBody), headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, requestEntity, String.class);

            String responseBody = response.getBody();
            log.info("极光短信发送响应: {}", responseBody);

            if (response.getStatusCode().is2xxSuccessful() && responseBody != null) {
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                if (jsonNode.has("msg_id")) {
                    String msgId = jsonNode.get("msg_id").asText();
                    log.info("成功发送验证码短信: mobile={}, type={}, msgId={}", mobile, type, msgId);
                    return SmsResult.success(msgId);
                }
            }

            return SmsResult.error("短信发送失败");
        } catch (RestClientException | JsonProcessingException e) {
            log.error("发送短信验证码异常: {}", e.getMessage(), e);
            return SmsResult.error("短信服务异常: " + e.getMessage());
        }
    }

    /**
     * 验证验证码
     *
     * @param msgId 消息ID
     * @param code  验证码
     * @return 验证结果
     */
    public boolean verifyCode(String msgId, String code) {
        try {
            String url = baseUrl + "/codes/" + msgId + "/valid";
            HttpHeaders headers = createAuthHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("code", code);

            HttpEntity<String> requestEntity = new HttpEntity<>(
                    objectMapper.writeValueAsString(requestBody), headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, requestEntity, String.class);

            String responseBody = response.getBody();
            log.info("极光验证码验证响应: {}", responseBody);

            if (response.getStatusCode().is2xxSuccessful() && responseBody != null) {
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                if (jsonNode.has("is_valid")) {
                    return jsonNode.get("is_valid").asBoolean();
                }
            }

            return false;
        } catch (RestClientException | JsonProcessingException e) {
            log.error("验证码验证异常: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 根据验证码类型获取模板ID
     */
    private String getTemplateIdByType(String type) {
        switch (type) {
            case "LOGIN":
                return tempIdLogin;
            case "REGISTER":
                return tempIdRegister;
            case "PASSWORD_RESET":
                return tempIdResetPassword;
            default:
                return null;
        }
    }

    /**
     * 创建认证请求头
     */
    private HttpHeaders createAuthHeaders() {
        HttpHeaders headers = new HttpHeaders();
        String auth = appKey + ":" + masterSecret;
        String encodedAuth = java.util.Base64.getEncoder().encodeToString(auth.getBytes());
        headers.add("Authorization", "Basic " + encodedAuth);
        return headers;
    }

    /**
     * 短信发送结果
     */
    @Data
    public static class SmsResult {
        private boolean success;
        private String msgId;
        private String errorMessage;

        public static SmsResult success(String msgId) {
            SmsResult result = new SmsResult();
            result.setSuccess(true);
            result.setMsgId(msgId);
            return result;
        }

        public static SmsResult error(String errorMessage) {
            SmsResult result = new SmsResult();
            result.setSuccess(false);
            result.setErrorMessage(errorMessage);
            return result;
        }
    }
}